package com.njiandan.johnson.vr360library.filters.base;

import android.content.Context;
import android.opengl.GLES20;
import android.opengl.Matrix;

import com.njiandan.johnson.vr360library.object.Plain;
import com.njiandan.johnson.vr360library.programs.GLOESProgram;
import com.njiandan.johnson.vr360library.textures.GLOESTexture;
import com.njiandan.johnson.vr360library.utils.TextureUtils;

/**
 * author：johnsonZhang on 2017/3/24 16:16
 * email：15915356@qq.com
 */
public class OESFilter extends AbsFilter {
    private GLOESProgram gloesProgram;
    private GLOESTexture gloesTexture;
    private Plain plain;

    // videoTextureMatrix
    private float[] mSTMatrix = new float[16];

    public OESFilter(Context context) {
        plain = new Plain(true);
        gloesProgram = new GLOESProgram(context);
        gloesTexture = new GLOESTexture();
        Matrix.setIdentityM(mSTMatrix, 0);
    }

    @Override
    public void init() {
        gloesProgram.create();
        gloesTexture.loadTexture();
    }

    @Override
    public void onPreDrawElements() {
        super.onPreDrawElements();
        gloesProgram.use();
        plain.uploadTexCoordinateBuffer(gloesProgram.getTextureCoordinateHandle());
        plain.uploadVerticesBuffer(gloesProgram.getPositionHandle());
        GLES20.glUniformMatrix4fv(gloesProgram.getMuSTMatrixHandle(), 1, false, mSTMatrix, 0);
    }

    @Override
    public void destroy() {
        gloesProgram.onDestroy();
        gloesTexture.deleteTexture();
    }

    @Override
    public void onDrawFrame(int textureId) {
        onPreDrawElements();
        TextureUtils.bindTextureOES(textureId, GLES20.GL_TEXTURE0, gloesProgram.getUTextureSamplerHandle(), 0);
        GLES20.glViewport(0, 0, surfaceWidth, surfaceHeight);
        plain.draw();
    }

    public GLOESProgram getGlOESProgram() {
        return gloesProgram;
    }

    public GLOESTexture getGlOESTexture() {
        return gloesTexture;
    }

    public float[] getSTMatrix() {
        return mSTMatrix;
    }
}
